package com.jcp.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.jcp.entity.Users;
import com.jcp.service.RegisterService;
import com.jcp.service.UserService;
import com.jcp.util.MD5Util;

@Controller
@RequestMapping(method=RequestMethod.GET)
@SessionAttributes("user")
public class RegisterController {
	
	//UserService的依赖注入
		@Autowired
		private  RegisterService regservice;
	
	/**
	 * 登录界面的注册方法
	 * @param users：User对象
	 * @return
	 */
	@PostMapping(value="register",produces="application/json;charset=utf-8")
	@ResponseBody
	public String ZhuCheUser(@ModelAttribute(value = "users")Users users) {
		//判断用户是否存在
		if(regservice.selectChong(users)||(users.getPassword().length()==0)) {
			
			return "注册失败";
		}else {
			regservice.ZhuCheUser(users);
			return "注册成功";
		}
	}
	/**
	 * 登录的方法
	 * @param user：Users对象
	 * @return String
	 */
	@PostMapping(value="registerlogin",produces="application/json;charset=utf-8")
	@ResponseBody
	public String LoginUser(@ModelAttribute(value="user")Users user) {
		
		//获取密码和手机号码
		String password=user.getPassword();
//		password=MD5Util.getEncodeByMd5(password);
		String PhoneNumber=user.getPhoneNumber();
		//获取User模糊查询出来的集合
		Users userlist = regservice.selectByOne(user);
		if(userlist!=null) {//用户登录
			//给session中设置用户名
//			user.setPassword(password);
			user.setUserName(userlist.getUserName());
			user.setCarNumber(userlist.getCarNumber());
			user.setMembership_expires_date(userlist.getMembership_expires_date());
			user.setRemainder(userlist.getRemainder());

			System.out.println(user);
			return "登录成功";
		}else {
		return "登录失败";//登录失败
		}
	}
	//解决sessio的异常
	@ModelAttribute("user")
	public Users getUser() {
		Users user = new Users();
		return user;
	}
	
	

}
